﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Serenity.Utility
{
    public static class ConfigHelper
    {
        public static T GetConfiguration<T>(Func<string, T> parseFunc, Func<T> defaultTValueFunc, [CallerMemberName]string key = "")
        {
            try
            {
                string rawConfigValue = ConfigurationManager.AppSettings[key];
                return !string.IsNullOrEmpty(rawConfigValue) ?
                        parseFunc(rawConfigValue) :
                        defaultTValueFunc();
            }
            catch (ConfigurationException)
            {
                // error handling logic
                return default(T);
            }
        }

        /// <summary>
        /// string类型，属性名和key不一样，默认值“FileSystemImageProvider”:
        /// TryGetValueFromConfig(_ => _, () => "FileSystemImageProvider", supressKey: "ImageProvider");
        /// 
        /// bool类型，默认值想要true:TryGetValueFromConfig(bool.Parse, () => true);
        /// 
        /// int类型，默认值为20:TryGetValueFromConfig(int.Parse, () => 20);
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="parseFunc"></param>
        /// <param name="defaultTValueFunc"></param>
        /// <param name="key"></param>
        /// <param name="supressKey"></param>
        /// <returns></returns>
        public static T TryGetValueFromConfig<T>(Func<string, T> parseFunc, Func<T> defaultTValueFunc, [CallerMemberName]string key = "", string supressKey = "")
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(supressKey))
                {
                    key = supressKey;
                }

                var node = ConfigurationManager.AppSettings[key];
                return !string.IsNullOrEmpty(node) ? parseFunc(node) : defaultTValueFunc();
            }
            catch (Exception)
            {
                return default(T);
            }
        }
    }
}
